package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("新增分类成功");//前台只要个code=1
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> page(Integer page, Integer pageSize) {
        //分页查询
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //添加排序条件，按照sort升序排序,然后按照修改时间降序排序
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");

        categoryService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(Long id) {
        //categoryService.removeById(id);
        //return categoryService.remove(id);
        categoryService.remove(id);
        return R.success("删除成功");
    }

    /**
     * 根据ID修改
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 添加菜品的下拉框请求
     * 根据type查询分类列表
     */
    @GetMapping("/list")
    public R<List<Category>> list(Integer type) {
        //构造条件
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(type != null, "type", type);
        //查询数据
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
